<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>微信安全登录</title>
    <style>
        .container {
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            text-align: center;
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        }
        #qrModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0,0,0,0.2);
            z-index: 1000;
        }
        .modal-close {
            position: absolute;
            right: 15px;
            top: 10px;
            cursor: pointer;
            font-size: 24px;
        }
        .loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 20px 0;
        }
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        button {
            padding: 12px 24px;
            font-size: 16px;
            background: #07c160;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        button:hover {
            background: #06ad56;
            transform: translateY(-2px);
        }
        #errorMsg {
            color: #e74c3c;
            margin: 15px 0;
            min-height: 24px;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>微信扫码登录</h1>
    <button onclick="openQRModal()">立即登录</button>

    <!-- 二维码模态框 -->
    <div id="qrModal">
        <div class="modal-close" onclick="closeQRModal()">&times;</div>
        <div class="loading">
            <div class="spinner"></div>
            <p>正在生成二维码...</p>
        </div>
        <img id="qrCodeImage" alt="微信登录二维码"
             style="max-width: 300px; display: none;">
        <div id="modalError" style="color: red; display: none;"></div>
    </div>

    <!-- 用户信息展示 -->
    <div id="userInfo" style="margin-top: 30px; display: none;">
        <h2>欢迎回来，<span id="nickname" style="color: #07c160;"></span>！</h2>
        <img id="avatar" src="" style="width: 80px; height: 80px; border-radius: 50%;">
    </div>

    <div id="errorMsg"></div>
</div>

<script>
    let authWindow = null;

    function openQRModal() {
        const modal = document.getElementById('qrModal');
        modal.style.display = 'block';

        // 先显示加载动画
        document.querySelector('.loading').style.display = 'flex';
        document.getElementById('qrCodeImage').style.display = 'none';
        document.getElementById('modalError').style.display = 'none';

        // 创建新的认证窗口
        if (authWindow && !authWindow.closed) {
            authWindow.close();
        }
        authWindow = window.open('/twxLogin', 'wechatAuth',
            'width=400,height=500,scrollbars=no,resizable=no');

        // 监听窗口关闭
        const checkClose = setInterval(() => {
            if (authWindow.closed) {
                clearInterval(checkClose);
                modal.style.display = 'none';
            }
        }, 500);

        // 获取二维码
        const qrImg = document.getElementById('qrCodeImage');
        qrImg.onload = () => {
            document.querySelector('.loading').style.display = 'none';
            qrImg.style.display = 'block';
        };
        qrImg.onerror = () => {
            document.getElementById('modalError').textContent = '二维码生成失败';
            document.getElementById('modalError').style.display = 'block';
        };
        qrImg.src = '/twxLogin?t=' + Date.now();
    }

    function closeQRModal() {
        document.getElementById('qrModal').style.display = 'none';
        if (authWindow && !authWindow.closed) {
            authWindow.close();
        }
    }

    // 消息监听（严格安全验证）
    window.addEventListener('message', function(e) {
        const allowedOrigins = [
            location.protocol + '//' + location.host,  // 当前域名
            'http://localhost:8080'                   // 开发环境
        ];

        if (!allowedOrigins.includes(e.origin)) {
            console.warn('拒绝非法来源:', e.origin);
            return;
        }

        try {
            const data = JSON.parse(e.data);

            if (data.error) {
                showError(data.error);
                return;
            }

            if (data.nickname) {
                document.getElementById('userInfo').style.display = 'block';
                document.getElementById('nickname').textContent = data.nickname;
                document.getElementById('avatar').src = data.headimgurl;
                closeQRModal();
            }
        } catch (error) {
            showError('登录信息异常');
            console.error('消息处理错误:', error);
        }
    });

    function showError(msg) {
        const errorDiv = document.getElementById('errorMsg');
        errorDiv.textContent = msg;
        setTimeout(() => errorDiv.textContent = '', 3000);
    }
</script>
</body>
</html>